package util

import (
	"os"
	"os/exec"
)

// ExecCmd 执行 command
func ExecCmd(scriptFile, cmdString string) ([]byte, error) {

	// 生成临时文件
	if CheckFileIsExist(scriptFile) {
		os.Remove(scriptFile)
	}
	file, err := os.Create(scriptFile)
	if err != nil {
		return nil, err
	}
	defer os.Remove(file.Name())
	defer file.Close()

	if _, err = file.WriteString(cmdString); err != nil {
		return nil, err
	}
	file.Close()

	return ExecScript(scriptFile)
}

// ExecScript exec script
func ExecScript(scriptPath string) ([]byte, error) {

	var cmd = exec.Command("cmd", "/c", scriptPath)
	return cmd.Output()
}

func CheckFileIsExist(filename string) bool {
	var exist = true
	if _, err := os.Stat(filename); os.IsNotExist(err) {
		exist = false
	}
	return exist
}
